//
//  XNOAuthViewController.swift
//  weibo
//
//  Created by 王向宁 on 16/5/22.
//  Copyright © 2016年 王向宁. All rights reserved.
//

import UIKit
import SVProgressHUD

class XNOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        
        //在load阶段,将根视图替换为webView
        view = webView
        
        webView.delegate = self
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        
        loadOauthPage()
    }
    
    //打来授权界面
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)!
        
        let req = NSURLRequest(URL: url)
        
        webView.loadRequest(req)
  
    }
    
    
 

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    

}

//设置导航条 监听按钮点击事件
extension XNOAuthViewController {
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(XNOAuthViewController.close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(XNOAuthViewController.testAccount))
        
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' "
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
}

extension XNOAuthViewController:UIWebViewDelegate {
    
    func  webViewDidStartLoad(webView: UIWebView) {
        //显示用户等待显示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        
        let successFlag = "code="
        
        if urlString.containsString(successFlag) {
            let range = urlString.rangeOfString(successFlag)!
            
            let code = urlString.substringFromIndex(range.endIndex)
            
            print(code,urlString)
            
            //获取code以后,应该使用code码 请求token
            XNUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code,finished: {
                (isSuccess) in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                
//                UIApplication.sharedApplication().keyWindow?.rootViewController = XNWelcomeViewController()
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })
            //不加载网页
            return false
            
        }
        
        return true
    
    }
    
}
